<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>收藏房源</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 50px auto;
            background: white;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .property-image {
            width: 100%;
            max-height: 400px;
            object-fit: cover;
            border-radius: 10px;
        }
        .property-details {
            margin-top: 20px;
            margin-left:80px;
        }
        .property-details h2 {
            margin: 0;
        }
        .property-details p {
            color: #555;
        }
        .property-details .price {
            font-size: 1.5em;
            color: #e74c3c;
        }
        .remove-button {
            margin-top: 150px;
            margin-left: 200px;
            padding: 10px 15px;
            font-size: 1em;
            cursor: pointer;
            border: none;
            border-radius: 5px;
            color: white;
            background-color: #e74c3c;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>收藏房源</h1>
        <hr style="width: 1288px;position: relative;right:20px">

    </div>
    <div id="property-content">
        <p>正在加载数据...</p>
    </div>
</div>

<script>
    const token = localStorage.getItem('token');
    document.addEventListener("DOMContentLoaded", function() {
        const userId = localStorage.getItem('userId');
        const apiUrl = `http://localhost:8080/user/getFavoriteByUserId?userId=${userId}`;

        fetch(apiUrl,
            {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                const propertyContent = document.getElementById('property-content');
                propertyContent.innerHTML = ''; // 清空之前的内容

                if (data.code === 1 && Array.isArray(data.data)) {
                    data.data.forEach(favorite => {
                        // 创建一个新的div元素来包含每个收藏项
                        const favoriteElement = document.createElement('div');
                        favoriteElement.classList.add('favorite-item'); // 添加一个CSS类，以便于样式管理

                        // 判断状态并设置状态文本
                        const statusText = favorite.status === 0 ? '已停售' : '在售中';

                        // 填充收藏项的内容
                        favoriteElement.innerHTML = `
                            <div style="display: flex">
                            <img  style="width:500px;height:300px" src="${favorite.imageUrl}" alt="${favorite.title}" class="property-image">
                            <div style="display:flex">
                              <div class="property-details">
                                <h2>${favorite.title}</h2>
                                <p>${favorite.description}</p>
                                <p><strong>房屋类型:</strong> ${favorite.type === 0 ? '二手房' : '新房'}</p>
                                <p class="price">价格: ¥${favorite.price.toLocaleString()}</p>
                                <p><strong>收藏日期:</strong> ${new Date(favorite.favoriteDate).toLocaleDateString()}</p>
                                <p><strong>状态:</strong> ${statusText}</p>
                            </div>
                            <div>
                                                            <button class="remove-button" onclick="handleRemoveFavorite(${favorite.favoriteId})">移除收藏</button>

</div>
</div>

</div>
                           <hr style="width: 1288px;position: relative;right:20px">

                        `;

                        // 将这个收藏项添加到内容容器中
                        propertyContent.appendChild(favoriteElement);
                    });
                } else {
                    propertyContent.innerHTML = '<p>无法加载数据，请稍后再试。</p>';
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                document.getElementById('property-content').innerHTML = '<p>加载数据时出错。</p>';
            });
    });

    function handleRemoveFavorite(favoriteId) {
        // 显示确认对话框
        const userConfirmed = confirm("确定要移除该收藏吗？");
        if (userConfirmed) {
            // 用户确认后，发送删除请求
            const deleteApiUrl = `http://localhost:8080/user/deleteFavoriteById?favoriteId=${favoriteId}`;

            fetch(deleteApiUrl, {
                method: 'DELETE' ,
                headers: {
                    'Authorization': `Bearer ${token}`
                }

            })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 1 ) {
                        alert('收藏已成功移除');
                        location.reload(); // 刷新页面以更新收藏状态
                    } else {
                        alert('移除收藏失败，请稍后再试');
                    }
                })
                .catch(error => {
                    console.error('Error deleting favorite:', error);
                    alert('移除收藏时出错，请稍后再试');
                });
        }
    }
</script>
</body>
</html>
